#!/usr/bin/env node

const { db } = require('../src/lib/db');
const { customers, products, inventory, orders, orderItems, orderActivities, inventoryHistory } = require('../src/lib/schema');
const { eq } = require('drizzle-orm');

async function testOrderLifecycle() {
  console.log('🚀 开始测试订单完整生命周期\n');

  try {
    // 1. 创建测试客户
    console.log('1. 创建测试客户...');
    const [testCustomer] = await db.insert(customers).values({
      name: '测试客户',
      email: 'test@example.com',
      phone: '13800138000',
      address: '测试地址'
    }).returning();
    console.log(`✅ 创建客户成功: ${testCustomer.name} (ID: ${testCustomer.id})`);

    // 2. 创建测试产品
    console.log('\n2. 创建测试产品...');
    const [testProduct] = await db.insert(products).values({
      name: '测试产品',
      description: '用于测试订单流程的产品',
      price: 100.0,
      sku: 'TEST001',
      category: '测试类别'
    }).returning();
    console.log(`✅ 创建产品成功: ${testProduct.name} (ID: ${testProduct.id})`);

    // 3. 设置库存
    console.log('\n3. 设置产品库存...');
    const [testInventory] = await db.insert(inventory).values({
      productId: testProduct.id,
      quantity: 10,
      lowStockThreshold: 2
    }).returning();
    console.log(`✅ 设置库存成功: 数量 ${testInventory.quantity}`);

    // 4. 创建订单
    console.log('\n4. 创建测试订单...');
    const [testOrder] = await db.insert(orders).values({
      customerId: testCustomer.id,
      totalAmount: 200.0,
      status: 'pending'
    }).returning();
    console.log(`✅ 创建订单成功: 订单 #${testOrder.id}, 金额: ¥${testOrder.totalAmount}`);

    // 5. 添加订单商品
    console.log('\n5. 添加订单商品...');
    const [orderItem] = await db.insert(orderItems).values({
      orderId: testOrder.id,
      productId: testProduct.id,
      quantity: 2,
      price: 100.0,
      subtotal: 200.0
    }).returning();
    console.log(`✅ 添加商品成功: 数量 ${orderItem.quantity}, 小计: ¥${orderItem.subtotal}`);

    // 6. 检查初始库存
    console.log('\n6. 检查初始库存状态...');
    const [initialInventory] = await db.select().from(inventory).where(eq(inventory.productId, testProduct.id));
    console.log(`📦 初始库存: ${initialInventory.quantity} 件`);

    // 7. 测试状态转换: pending → paid (应该锁定库存)
    console.log('\n7. 测试状态转换: pending → paid...');
    await testStatusTransition(testOrder.id, 'paid', '库存锁定');

    // 8. 验证库存锁定
    console.log('\n8. 验证库存锁定...');
    const [lockedInventory] = await db.select().from(inventory).where(eq(inventory.productId, testProduct.id));
    console.log(`🔒 锁定后库存: ${lockedInventory.quantity} 件 (应该为 8)`);
    
    if (lockedInventory.quantity !== 8) {
      throw new Error(`库存锁定失败! 期望: 8, 实际: ${lockedInventory.quantity}`);
    }

    // 9. 检查库存历史记录
    console.log('\n9. 检查库存变更记录...');
    const inventoryChanges = await db.select().from(inventoryHistory).where(eq(inventoryHistory.productId, testProduct.id));
    console.log(`📊 库存变更记录: ${inventoryChanges.length} 条`);
    inventoryChanges.forEach(change => {
      console.log(`   - ${change.notes}: ${change.previousQuantity} → ${change.newQuantity}`);
    });

    // 10. 测试状态转换: paid → shipped
    console.log('\n10. 测试状态转换: paid → shipped...');
    await testStatusTransition(testOrder.id, 'shipped', '发货处理');

    // 11. 测试状态转换: shipped → delivered
    console.log('\n11. 测试状态转换: shipped → delivered...');
    await testStatusTransition(testOrder.id, 'delivered', '订单完成');

    // 12. 验证最终库存
    console.log('\n12. 验证最终库存状态...');
    const [finalInventory] = await db.select().from(inventory).where(eq(inventory.productId, testProduct.id));
    console.log(`🏁 最终库存: ${finalInventory.quantity} 件 (应该保持为 8)`);

    // 13. 检查活动记录
    console.log('\n13. 检查订单活动记录...');
    const activities = await db.select().from(orderActivities).where(eq(orderActivities.orderId, testOrder.id));
    console.log(`📋 活动记录数量: ${activities.length}`);
    activities.forEach(activity => {
      console.log(`   - [${new Date(activity.createdAt * 1000).toLocaleString('zh-CN')}] ${activity.description}`);
    });

    // 14. 验证最终订单状态
    console.log('\n14. 验证最终订单状态...');
    const [finalOrder] = await db.select().from(orders).where(eq(orders.id, testOrder.id));
    console.log(`✅ 订单最终状态: ${finalOrder.status} (应该是 delivered)`);

    if (finalOrder.status !== 'delivered') {
      throw new Error(`订单状态不正确! 期望: delivered, 实际: ${finalOrder.status}`);
    }

    console.log('\n🎉 所有测试通过! 订单生命周期完整验证成功!');
    console.log('\n📊 测试总结:');
    console.log('   - 客户创建: ✅');
    console.log('   - 产品创建: ✅');
    console.log('   - 库存设置: ✅');
    console.log('   - 订单创建: ✅');
    console.log('   - 状态转换: ✅ (pending → paid → shipped → delivered)');
    console.log('   - 库存管理: ✅ (自动锁定和记录)');
    console.log('   - 活动记录: ✅');

  } catch (error) {
    console.error('\n❌ 测试失败:', error.message);
    console.error(error.stack);
    process.exit(1);
  }
}

async function testStatusTransition(orderId, newStatus, description) {
  console.log(`   🚚 ${description}...`);
  
  const [currentOrder] = await db.select().from(orders).where(eq(orders.id, orderId));
  
  const response = await fetch(`http://localhost:3000/api/orders/${orderId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ status: newStatus }),
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(`状态转换失败 (${currentOrder.status} → ${newStatus}): ${errorData.error}`);
  }

  const updatedOrder = await response.json();
  console.log(`   ✅ 状态转换成功: ${currentOrder.status} → ${updatedOrder.status}`);
}

// 启动测试
if (require.main === module) {
  testOrderLifecycle().catch(console.error);
}

module.exports = { testOrderLifecycle };